package com.ushine.web.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushine.web.base.mapper.RoleAndDataPermissionMapper;
import com.ushine.web.base.model.relation.RoleAndDataPermissionDO;
import com.ushine.web.base.service.IRoleAndDataPermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: yls
 * @Date: 2022/02/15 23:45
 * @Description:
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleAndDataPermissionServiceImpl extends ServiceImpl<RoleAndDataPermissionMapper, RoleAndDataPermissionDO>
        implements IRoleAndDataPermissionService {

    @Override
    public Boolean insertBatchRoleAndDataPermissions(List<RoleAndDataPermissionDO> roleAndDataPermissions) {
        roleAndDataPermissions = Optional.ofNullable(roleAndDataPermissions).orElse(new ArrayList<>(0));
        Set<Long> roleIds = roleAndDataPermissions.stream().map(RoleAndDataPermissionDO::getRoleId).collect(Collectors.toSet());
        LambdaQueryWrapper<RoleAndDataPermissionDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(RoleAndDataPermissionDO::getRoleId, roleIds);
        remove(lambdaQueryWrapper);
        return saveBatch(roleAndDataPermissions);
    }

    @Override
    @Transactional(readOnly = true)
    public List<RoleAndDataPermissionDO> listRoleAndDataPermissions(Long roleId) {
        LambdaQueryWrapper<RoleAndDataPermissionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleAndDataPermissionDO::getRoleId, roleId)
                .select(RoleAndDataPermissionDO::getDataPermissionId);
        return Optional.ofNullable(list(queryWrapper)).orElse(new ArrayList<>(0));
    }
}
